package com.minxi.web.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class DelServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理表单数据乱码问题
        req.setCharacterEncoding("utf-8");
        //1.获取请求数据
        String id= req.getParameter("id");
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        //2.请求数据库
        try {
            //1.注册驱动 JDBC
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接
            String url = "jdbc:mysql://localhost:3306/student?serverTimezone=Asia/Shanghai";
            String user = "root";
            String pwd = "123456";
            connection = DriverManager.getConnection(url, user, pwd);
            //3.编辑SQL语句
            String sql = "delete from user_info where id=?;";
            //得到执行对象
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, Integer.parseInt(id));
            int rs = preparedStatement.executeUpdate();
            if (rs > 0) {
            /*    resp.sendRedirect("jsp/home.jsp");
            } else {*/
                //1.列表数据要刷新(重新查询)
                getUserInfo(req,resp);
                //2.跳转列表页面
                resp.sendRedirect("jsp/add.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != preparedStatement) {
                    preparedStatement.close();
                }
                if (null != connection) {
                    connection.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
